package com.cmic.rcs.emoji.service.impl;

import com.cmic.origin.DataEncryptUtil;
import com.cmic.rcs.emoji.common.UserContext;
import com.cmic.rcs.emoji.entity.dto.EnterpriseMemberRequest;
import com.cmic.rcs.emoji.entity.dto.PageRequest;
import com.cmic.rcs.emoji.entity.pojo.TEnterpriseMember;
import com.cmic.rcs.emoji.entity.vo.EnterpriseMemberVo;
import com.cmic.rcs.emoji.entity.vo.PageResult;
import com.cmic.rcs.emoji.mapper.TEnterpriseMemberMapper;
import com.cmic.rcs.emoji.service.EnterpriseMemberService;
import com.cmic.rcs.emoji.util.AddressBookApiUtil;
import com.cmic.rcs.emoji.util.SessionManageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class EnterpriseMemberServiceImpl implements EnterpriseMemberService {
    @Autowired
    private SessionManageUtil sessionManageUtil;
    
    @Autowired
    private TEnterpriseMemberMapper enterpriseMemberMapper;

    @Autowired
    private DataEncryptUtil dataEncryptUtil;

    @Autowired
    private AddressBookApiUtil addressBookApiUtil;

    
    @Override
    public PageResult<EnterpriseMemberVo> listMembers(String enterpriseCode, PageRequest pageRequest) {
        // 设置分页参数
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        
        // 查询企业成员列表
        List<TEnterpriseMember> members = enterpriseMemberMapper.selectListAll(enterpriseCode);
        //根据时间倒序
        members.sort((o1, o2) -> o2.getUpdateTime().compareTo(o1.getUpdateTime()));

        PageInfo<TEnterpriseMember> pageInfo = new PageInfo<>(members);
        
        // 转换为VO对象
        List<EnterpriseMemberVo> memberVos = new ArrayList<>();
        for (TEnterpriseMember member : members) {
            EnterpriseMemberVo vo = new EnterpriseMemberVo();
            vo.setId(member.getId());
            vo.setMemberName(member.getMemberName());
            // 对手机号进行解密处理

            if (member.getMemberAccount() != null) {
                vo.setMemberAccount(dataEncryptUtil.decrypt(member.getMemberAccount())); // 对手机号进行解密处理
            }

            vo.setMemberAccount(member.getMemberAccount());
            vo.setMemberStatus(member.getMemberStatus());
            vo.setCreateTime(member.getCreateTime().toString());
            vo.setCreateBy(member.getCreateBy());
            memberVos.add(vo);
        }
        
        // 构建分页结果
        PageResult<EnterpriseMemberVo> result = new PageResult<>();
        result.setTotal(pageInfo.getTotal());
        result.setList(memberVos);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addMember(String enterpriseCode, EnterpriseMemberRequest request) {
        // 1. 校验手机号格式
        String phoneNumber = request.getPhoneNumber();
        if (!phoneNumber.matches("^\\d{11}$")) {
            throw new RuntimeException("请输入有效的手机号码");
        }

        try {
            // 验证 enterpriseCode 是否为 null 或空
            if (enterpriseCode == null || enterpriseCode.trim().isEmpty()) {
                throw new NumberFormatException("Enterprise code is null or empty");
            }

            // 清理并验证 enterpriseCode
            String cleanEnterpriseCode = enterpriseCode.replaceAll("[^\\d]", "");

            if (cleanEnterpriseCode.isEmpty()) {
                throw new NumberFormatException("Enterprise code contains no valid digits: " + enterpriseCode);
            }

            // 检查数字是否在合理范围内
            Long orgId = Long.valueOf(cleanEnterpriseCode);

            // 可选：添加业务逻辑验证
            if (orgId <= 0) {
                throw new NumberFormatException("Enterprise code must be positive: " + orgId);
            }

            boolean isInOrg = addressBookApiUtil.checkMobileInEnterprise(orgId, phoneNumber);
            if (!isInOrg) {
                throw new RuntimeException("该手机号不是当前企业成员");
            }
        } catch (NumberFormatException e) {
            log.error("企业编号格式错误: {}", enterpriseCode, e);
            throw new RuntimeException("企业编号格式错误");
        }

        //手机号加密，后面需要数据库比对
        phoneNumber = dataEncryptUtil.encrypt(phoneNumber);
        
        // 3. 检查手机号是否已在其他企业添加
        List<TEnterpriseMember> tEnterpriseMembers = enterpriseMemberMapper.selectListbyPhone(phoneNumber);
        if (!tEnterpriseMembers.isEmpty()) {
            throw new RuntimeException("该手机号已添加到其他企业");
        }

        // 4. 创建企业成员记录
        TEnterpriseMember member = new TEnterpriseMember();
        member.setEnterpriseCode(enterpriseCode);
        member.setMemberAccount(phoneNumber);
        // 从通讯录获取成员姓名
        Long orgId = Long.valueOf(enterpriseCode);
        String memberName = addressBookApiUtil.getMemberNameByPhone(orgId, phoneNumber);
        if (memberName != null){
            member.setMemberName(memberName);
        }else {
            throw new RuntimeException("获取成员姓名失败");
        }
        member.setMemberStatus(1); // 默认为启用状态
        member.setCreateTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());
        // 从当前登录用户获取创建人信息
        member.setCreateBy(UserContext.getUserDto().getUsername());
        
        // 5. 保存到数据库
        enterpriseMemberMapper.insertOne(member);
        log.info("添加企业成员成功，企业编码：{}，手机号：{}", enterpriseCode, phoneNumber);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMember(Long memberId) {
        // 检查成员是否存在
        Optional<TEnterpriseMember> member = enterpriseMemberMapper.selectByPrimaryKey(memberId);
        if (member.isEmpty()) {
            throw new RuntimeException("成员不存在");
        }

        // 获取成员手机号，用于强制下线
        String phoneNumber = member.get().getMemberAccount();

        // 先调用强制下线接口，让用户下线
        if (phoneNumber != null && phoneNumber.length() == 11) {
            boolean logoutResult = sessionManageUtil.forceLogoutByPhone(phoneNumber);
            log.info("强制下线用户[{}]，结果：{}", "******" + phoneNumber.substring(6), logoutResult);
        }

        // 删除成员记录
        enterpriseMemberMapper.deleteByPrimaryKey(memberId);
        log.info("删除企业成员成功，成员ID：{}", memberId);

    }


}